<script setup lang="ts">
import { ref, onMounted } from 'vue'
import VideoPlayer from './components/VideoPlayer.vue'

// https://p.bvvvvvvv7f.com/video/buxingzhiyejiandingshishizezuiqiang/%E7%AC%AC12%E9%9B%86/index.m3u8
const videoUrl = ref('')
const currentTime = ref(0)

// 从 localStorage 加载上次播放的 URL 和时间
const loadLastPlayed = () => {
  const lastUrl = localStorage.getItem('lastPlayedUrl')
  const lastTime = localStorage.getItem('lastPlayedTime')
  if (lastUrl) {
    videoUrl.value = lastUrl
    currentTime.value = lastTime ? parseFloat(lastTime) : 0
  }
}

// 保存当前 URL 和时间到 localStorage
const saveCurrentState = (time: number) => {
  localStorage.setItem('lastPlayedUrl', videoUrl.value)
  localStorage.setItem('lastPlayedTime', time.toString())
}

// 处理视频时间更新
const handleTimeUpdate = (time: number) => {
  saveCurrentState(time)
}

// 处理表单提交
const handleSubmit = () => {
  if (videoUrl.value) {
    // 更新 URL 而不重新加载页面
    const newUrl = new URL(window.location.href)
    newUrl.searchParams.set('url', videoUrl.value)
    window.history.pushState({}, '', newUrl)
    
    // 保存到 localStorage
    saveCurrentState(0)
  }
}

onMounted(() => {
  // 首先检查 URL 参数
  const urlParams = new URLSearchParams(window.location.search)
  const urlParam = urlParams.get('url')
  
  if (urlParam) {
    videoUrl.value = urlParam
    saveCurrentState(0)
  } else {
    // 如果没有 URL 参数，从 localStorage 加载
    loadLastPlayed()
  }
})
</script>

<template>
  <div class="flex flex-col items-center gap-5 p-5 max-w-3xl mx-auto">
    <div class="flex gap-2.5 w-full">
      <input 
        v-model="videoUrl"
        type="text"
        placeholder="输入 M3U8 URL"
        class="flex-1 px-3 py-2 border border-gray-300 rounded text-base focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
      />
      <button 
        @click="handleSubmit" 
        class="px-5 py-2 bg-green-500 text-white rounded text-base font-medium hover:bg-green-600 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2"
      >
        播放
      </button>
    </div>

    <div v-if="videoUrl" class="w-full">
      <VideoPlayer
        :src="videoUrl"
        :currentTime="currentTime"
        @timeupdate="handleTimeUpdate"
      />
    </div>
  </div>
</template>
